/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.cj.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cj.common.exception.BaseException;
import com.cj.common.utils.DateUtil;
import com.cj.user.dao.SysCaptchaDao;
import com.cj.user.entity.SysCaptchaEntity;
import com.cj.user.service.SysCaptchaService;
import com.google.code.kaptcha.Producer;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;

/**
 * 验证码
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysCaptchaService")
public class SysCaptchaServiceImpl extends ServiceImpl<SysCaptchaDao, SysCaptchaEntity> implements SysCaptchaService {
    @Autowired
    private Producer producer;

    @Override
    public void getCaptcha(HttpServletResponse response, String uuid) {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        // 生成文字验证码
        String code = producer.createText();

        SysCaptchaEntity captchaEntity = new SysCaptchaEntity();
        captchaEntity.setUuid(uuid);
        captchaEntity.setCode(code);
        // 5分钟后过期
        captchaEntity.setExpireTime(DateUtil.addDateMinutes(new Date(), 5));
        this.save(captchaEntity);

        BufferedImage image = producer.createImage(code);

        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            ImageIO.write(image, "jpg", out);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BaseException(e.getMessage());
        } finally {
            // 关闭输出流
            try {
                IOUtils.close(out);
            } catch (IOException e) {
                log.error(e.getMessage());
                // todo
                // 当在finally块中使用return、throw时，编译器不会再对try、catch块中的非运行时异常进行检查，JVM不会再去捕获try块、
                // catch块中的异常，程序的输出以finally块为准，即finally块的返回值或者finally块中抛出的异常。
                // 当在try块或catch块中遇到return语句时，finally块将在方法返回之前被执行。finally块中的return语句会覆盖try块、
                // catch块中的return语句。合理的做法是在 finally 块之后使用return语句。
                throw new BaseException(e.getMessage());
            }
        }
    }

    @Override
    public boolean validate(String uuid, String code) {
        SysCaptchaEntity captchaEntity = this.getOne(new QueryWrapper<SysCaptchaEntity>().eq("uuid", uuid));
        if(captchaEntity == null){
            return false;
        }

        //删除验证码
        this.removeById(uuid);

        if(captchaEntity.getCode().equalsIgnoreCase(code) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()){
            return true;
        }

        return false;
    }
}
